package cn.theten52.demo.patterns.design.behavior.interpreter.update1;

import java.util.ArrayList;
import java.util.List;

/**
 * Java 解释器
 *
 * @author wangjin
 * @date 2021/1/6
 */
public class Calculator {

    public static final char PLUS = '+';
    public static final char MINUS = '-';

    public int calc(String exprString) {
        if ((exprString == null) || exprString.length() == 0) {
            throw new IllegalArgumentException("exprString is empty");
        }

        List<Expression> expressionList = new ArrayList<>();

        for (char c : exprString.toCharArray()) {
            if (c == PLUS || c == MINUS) {
                expressionList.add(new Operator(c));
                continue;
            }
            if (Character.isDigit(c)) {
                expressionList.add(new Operand(c));
            }
        }

        Context context = new Context();

        for (Expression expression : expressionList) {
            expression.evaluate(context);
        }

        return context.getValue();
    }
}
